
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import org.jibble.pircbot.*;

import java.util.*;

public class LogBot extends PircBot {

	// Remember up to 10 things that happened in the channel.
	private ContextList contextList = new ContextList(10);
	private CurrentTime now = new CurrentTime();

	public static void main(String[] args) throws Exception {



		LogBot bot = new LogBot();

		// Connect to a server and join a channel.

		bot.connect("irc.lessthan3.net");

		bot.joinChannel("#zubac");

	}

	// Constructor used to set the name of the bot.
	public LogBot() {

		this.setName("LogBot");

		this.setLogin("Fluebot3");

	}

	// Handle on-channel messages.
	public void onMessage(String channel, String sender,
			String login, String hostname, String message) {

		contextList.add(now + " <" + sender + "> " + message);

	}

	// Handle actions.
	public void onAction(String sender, String login,
			String hostname, String target, String action) {

		contextList.add(now + " * " + sender + " " + action);

	}

	// Handle people joining the channel.
	public void onJoin(String channel, String sender,
			String login, String hostname) {

		if (!sender.equals(getName())) {

			// Send out the history of messages to the new channel user.

			Iterator messageIt = contextList.iterator();
			sendMessage(sender, "This is the 10 last things that have happened in " + channel);

			while (messageIt.hasNext()) {


				sendMessage(sender, messageIt.next().toString());

			}

		}

	}
}

class ContextList extends Vector {

	private int maxListSize;

	public ContextList(int maxListSize) {

		this.maxListSize = maxListSize;

	}

	public boolean add(Object o) {

		if (this.size() >= maxListSize) {

			// Remove the first item if the list is full.

			this.remove(0);

		}

		// Add the new item to the end of the list.

		return super.add(o);

	}
}

class CurrentTime {

	private SimpleDateFormat shortDateFormat = new SimpleDateFormat("H:mm");
	private FieldPosition fp = new FieldPosition(0);

	public String toString() {

		Date now = new Date();

		StringBuffer output = new StringBuffer();

		try {

			shortDateFormat.format(now, output, fp);

		} catch (NullPointerException e) {
			// Date cannot be null. Ignore this.
		}

		return output.toString();

	}
}
